package com.np.controller;

import com.np.model.Error;
import com.np.model.Product;
import com.np.model.User;
import com.np.util.HibernateUtil;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/13.
 */
@Controller
//@RequestMapping("user")
public class UserControllr {
    private static Logger log = (Logger) LogManager.getLogger(UserControllr.class.getName());



    @RequestMapping("/hello")
    public String hello(Model model){

        List<User> list = new ArrayList<>();

        for(int i=0;i<10;i++)
        {
            User user = new User();
            user.setEmail("���Ƿ�");
            user.setId(i);
            user.setName("wyf");
            user.setLevel(5);
            user.setTel("15151");

            list.add(user);
        }
        model.addAttribute("list",list);
        return "hello";
    }

    @RequestMapping("/register")
    public String register()
    {
        return "register";
    }

    @RequestMapping(value = "/register_save",method = RequestMethod.POST)
    public String registerSavae(String email,String password,String passwordRepeat,Model model)
    {
        log.info("---------------------------------------------");
        log.info(email+"         "+password+"        "+passwordRepeat);

        Error error = new Error();
        String regex = "\\w+(\\.\\w)*@\\w+(\\.\\w{2,3}){1,3}";

        if(!(email.matches(regex))){
            error.setPassword("邮箱格式错误");
            model.addAttribute("error",error);
            return "register";

        }

        if(!password.equals(passwordRepeat)){
            error.setPassword("密码不一致");
            model.addAttribute("error",error);
            return "register";
        }
        if(password.equals("")||email.equals("")){
            error.setPassword("密码不能为空");
            model.addAttribute("error",error);
            return "register";
        }



        Session session = HibernateUtil.getSessionFactory().openSession();
        User user = new User();
        user.setPassword(password);
        user.setEmail(email);
        log.info("test"+"-----------------------------------------------------------------"+user.getName());

        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();
        return "login";
    }

    @RequestMapping("/login")
    public String login(Model model){

        Error error = new Error();
        model.addAttribute("error",error);
        return "login";
    }

    @RequestMapping("/logindo")
    public String loginDo(String email, String password, HttpSession httpSession,Model model){
        log.info("----------"+email+"-----------------"+password+"-----------------------");

        Error error = new Error();
        String regex = "\\w+(\\.\\w)*@\\w+(\\.\\w{2,3}){1,3}";

        if(!(email.matches(regex))){
            error.setEmail("邮箱格式错误");
            model.addAttribute("error",error);
            return "login";

        }
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "from User ";
        Query query = session.createQuery(hql);

        List<User> users = query.list();
        for(User i : users){
            if(email.equals(i.getEmail())&&password.equals(i.getPassword())){
                httpSession.setAttribute("user",i);
                if(i.getLevel()>=1)
                {
                    User u = (User) httpSession.getAttribute("user");
                    log.info("--------------------------------------------"+i.getName());
                    return "admin/admin";
                }
                return "redirect:/home";
            }
        }


        if(password.equals(password)){
            error.setPassword("邮箱或密码错误");
            model.addAttribute("error",error);
            return "login";
        }
        return "login";

    }

    @RequestMapping("/home")
    public String home(Model model){

        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "from Product";
        Query query = session.createQuery(hql);

        List<Product> productList = query.list();
        List<Product> productRouter = new ArrayList<>();
        List<Product> productSwitch = new ArrayList<>();
        List<Product> productPeijian = new ArrayList<>();
        List<Product> productStore = new ArrayList<>();


        for (Product p:productList
             ) {
            if(p.getClassifty().equals("路由器"))
            {
                productRouter.add(p);
            }else if(p.getClassifty().equals("交换机")){
                productSwitch.add(p);

            }else  if(p.getClassifty().equals("网络配件"))
            {
                productPeijian.add(p);
            }else if(p.getClassifty().equals("网络存储")){
                productStore.add(p);
            }
            
        }

        model.addAttribute("productRouter",productRouter);
        model.addAttribute("productSwitch",productSwitch);
        model.addAttribute("productPeijian",productPeijian);
        model.addAttribute("productStore",productStore);

        return "home";
    }


    /**
     * 用户指南
     * @return
     */
    @RequestMapping("/zhinan")
    public String zhinan(){
        return "zhinan";
    }



    @RequestMapping("/buquan")
    public String buquan(HttpSession session){

        User user = (User) session.getAttribute("user");
        if(user == null){
            return "home";
        }

        return "buquan";
    }


    @RequestMapping(value = "/buquanDo",method = RequestMethod.POST)
    public String buquanDo(String name,String address,String tel,HttpSession session){

        User user = (User) session.getAttribute("user");
        if(user == null){
            return "home";
        }

        int id = user.getId();


        Session s = HibernateUtil.getSessionFactory().openSession();
        User u = s.load(User.class,id);
        u.setAddress(address);
        u.setName(name);
        u.setTel(tel);
        s.close();



        Session s2 = HibernateUtil.getSessionFactory().openSession();
        s2.beginTransaction();
        s2.update(u);
        s2.getTransaction().commit();


        return "redirect:buquan";
    }

}
